﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using NymphsLib.CommonUtilities;
using MovieBrowser.Controller;
using MovieBrowser.Event;
using MovieBrowser.Model;
using MovieBrowser.Presentation.Events;
using MovieBrowser.Presentation.Forms;
using MovieBrowser.Util;

namespace MovieBrowser.Presentation.List
{
    public partial class VirtualTreeView : UserControl, IMovieList, IDebugLogEvent
    {
        public MovieBrowserController Controller { get; set; }

        readonly SaveFileDialog _saveFileDialog = new SaveFileDialog();
        readonly OpenFileDialog _openFileDialog = new OpenFileDialog();

        public VirtualTreeView()
        {
            InitializeComponent();
            movieListView.Font = Properties.Settings.Default.ListFont;
            InitializeVirtualTree();
        }

        public Movie SelectedMovie { get { return movieListView.SelectedObject as Movie; } }

        public IList<Movie> SelectedMovies { get { return movieListView.SelectedObjects.Cast<Movie>().ToList(); } }

        public void UpdateNode(Movie movie)
        {
            Controller.UpdateMovieNode(SelectedMovie, movie);
        }

        #region Events
        public event EventHandler MovieSelectionChange;
        public event EventHandler DebugText;
        public event EventHandler CopyMovies;
        public event EventHandler Enqueue;
        public event EventHandler OnWebsiteRequest;
        //
        public void InvokeOnMovieSelectionChange(EventArgs e)
        {
            var handler = MovieSelectionChange;
            if (handler != null) handler(this, e);
        }
        //
        public void InvokeOnDebugText(Exception exception)
        {
            var handler = DebugText;
            if (handler != null) handler(this, new DebugTextEventArgs(exception));
        }
        public void InvokeOnDebugText(string text)
        {
            var handler = DebugText;
            if (handler != null) handler(this, new DebugTextEventArgs(text));
        }
        //
        public void InvokeOnWebsiteRequest(EventArgs e)
        {
            var handler = OnWebsiteRequest;
            if (handler != null) handler(this, e);
        }
        //
        public void InvokeCopyMovies(CopyMoviesEventArgs e)
        {
            var handler = CopyMovies;
            if (handler != null) handler(this, e);
        }
        //
        public void InvokeEnqueue(CopyMoviesEventArgs e)
        {
            var handler = Enqueue;
            if (handler != null) handler(this, e);
        }
        #endregion
        
        private void TbLoadVirtualFoldersClick(object sender, EventArgs e)
        {
            LoadVirtualTree();
        }

        private void TbRemoveItemClick(object sender, EventArgs e)
        {
            foreach (ListViewItem selectedItem in movieListView.SelectedItems)
            {
                movieListView.Items.Remove(selectedItem);
            }
        }

        private void TbSaveVirtualTreeClick(object sender, EventArgs e)
        {
            _saveFileDialog.Filter = @"Movie XML|*.xml";
            if (_saveFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                var roots = (ArrayList)movieListView.Roots;
                var movies = roots.Cast<Movie>().ToList();

                var serializer = new VirtualMovieFolderSerializer();
                serializer.SerializeTreeView(movies, _saveFileDialog.FileName);
            }
        }

        private void TbUpdateSelectedVirtualItemsClick(object sender, EventArgs e)
        {
            UpdateMovieInfo(movieListView.SelectedObjects.Cast<Movie>().ToList());
        }

        private void tbSearchImdb_Click(object sender, EventArgs e)
        {

        }

        private void tbSearchGoogle_Click(object sender, EventArgs e)
        {

        }

        private void SearchTextBoxSearchStarted(object sender, EventArgs e)
        {
            ComponentUtility.TimedFilter(movieListView, searchTextBox.Text);

        }

        private void SearchTextBoxSearchCancelled(object sender, EventArgs e)
        {
            ComponentUtility.TimedFilter(movieListView, "");

        }

        private void TreeListViewSelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                var movie = (Movie)(movieListView.SelectedObject);
                var eventArgs = new MovieEventArgs(movie, "SelectionChanged");
                InvokeOnMovieSelectionChange(eventArgs);
            }
            catch (Exception exception) { Logger.Exception(exception, 123); }
        }

        private void TreeListViewDoubleClick(object sender, EventArgs e)
        {
            if (movieListView.SelectedObject != null)
                Controller.SearchMovie(MovieBrowserController.ImdbSearch, (Movie)movieListView.SelectedObject);

        }

        private void TreeListViewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter) return;
            if (movieListView.SelectedObject != null)
                Controller.SearchMovie(MovieBrowserController.ImdbSearch, (Movie)movieListView.SelectedObject);

        }


        private void LoadVirtualTree()
        {
            _openFileDialog.Filter = @"Movie XML|*.xml";
            if (_openFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                var roots = new ArrayList();
                var serializer = new VirtualMovieFolderSerializer();
                var movie = serializer.DeserializeTreeView(_openFileDialog.FileName);
                foreach (var m in movie.Children)
                    roots.Add(m);
                movieListView.Roots = roots;
            }
        }

        private void UpdateMovieInfo(IList<Movie> movies)
        {
            var f = new UpdateMovieInformation(movies);
            f.Show(this);
        }

        void InitializeVirtualTree()
        {
            movieListView.CanExpandGetter = delegate(object x)
            {
                return ((Movie)x).IsFolder;
            };

            movieListView.ChildrenGetter = delegate(object x)
            {
                var movie = (Movie)x;
                try
                {
                    return movie.Children;
                }
                catch (UnauthorizedAccessException ex)
                {
                    MessageBox.Show(this, ex.Message, @"ObjectListViewDemo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return new ArrayList();
                }
            };

            // Draw the system icon next to the name
            //var helper = new SysImageListHelper(this.treeListView1);
            olvColVirtualTitle.ImageGetter = delegate(object x)
            {
                return ((Movie)x).ImageIndex;
            };
        }

        private void UpdateItemsToolStripMenuItemClick(object sender, EventArgs e)
        {
            var children = ((Movie)movieListView.SelectedObject).Children;
            new UpdateMovieInformation(children).Show();

        }

        private void UpdateSelectedItemsToolStripMenuItemClick(object sender, EventArgs e)
        {
            UpdateMovieInfo(movieListView.SelectedObjects.Cast<Movie>().ToList());
        }

        private  void TreeListViewFormatRow(object sender, BrightIdeasSoftware.FormatRowEventArgs e)
        {
            ComponentUtility.FormatRow(sender, e);
        }

        public void ShowGroup(bool group)
        {
        }

        public void UpdateFont(System.Drawing.Font font)
        {
            movieListView.Font = font;
        }

    }
}
